﻿//#define test

using OestsDataBase;
using OestsServer.Net;
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using Utils;

namespace OestsServer
{
    public class Program
    {

        [DllImport("User32.dll ", EntryPoint = "FindWindow")]
        private static extern int FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll ", EntryPoint = "GetSystemMenu")]
        extern static IntPtr GetSystemMenu(IntPtr hWnd, IntPtr bRevert);

        [DllImport("user32.dll ", EntryPoint = "RemoveMenu")]
        extern static int RemoveMenu(IntPtr hMenu, int nPos, int flags);

        const string title = "运营和专业设备三维仿真培训系统服务器";

        const string INSTANCE_NAME = "_OESTS_SERVER_";

        static void Main(string[] args)
        {
            if (!CreateInstance(INSTANCE_NAME))
            {
                Console.CursorVisible = false;
                int count = 8;
                Console.WriteLine("");
                Console.WriteLine($"\t*** 该程序已经运行，请勿重复运行 ***");
                Console.WriteLine("");
                Console.WriteLine($"\t           正在退出... ({count}) ");

                while (count >= 0)
                {
                    Console.SetCursorPosition(0, Console.CursorTop - 1);
                    Console.WriteLine($"\t           正在退出... ({count}) ");
                    Thread.Sleep(1000);
                    --count;
                }
                Environment.Exit(0);
            }

            //  当某个异常未被捕获时出现。主要指的是非UI线程
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);


            /* 设置窗口样式 */
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);

            Console.WindowWidth = 120;
            Console.BufferWidth = 220;//240 为最大值 保证可以换行
            Console.BufferHeight = 1000;

            Console.Title = title;
            //与控制台标题名一样的路径
            //  string fullPath = System.Environment.CurrentDirectory + "\\" + title + ".exe";
            //根据控制台标题找控制台
            int WINDOW_HANDLER = FindWindow(null, Console.Title);

            //找关闭按钮
            IntPtr CLOSE_MENU = GetSystemMenu((IntPtr)WINDOW_HANDLER, IntPtr.Zero);
            int SC_CLOSE = 0xF060;
            //关闭按钮禁用
            //RemoveMenu(CLOSE_MENU, SC_CLOSE, 0x0);
            Console.CancelKeyPress += new ConsoleCancelEventHandler(CloseConsole);


            //检查数据库
            if (!DBManager.TryConnectDB())
            {
                LogNetDebug.LogError("错误:连接数据库失败，请检查数据库，并重新启动服务器！");
                Console.ReadKey();
            }
            DBManager.CreateBaseTable();
            LogNetDebug.LogInfo(SqlHelper.ip);

            /* 启动服务器 */
            ServerController server = new ServerController();
            server.Start();
            MyDebug.WhileReadKey();
            Console.ReadKey();
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (e.ExceptionObject is System.Exception)
            {
                Exception ex = (System.Exception)e.ExceptionObject;
                LogNetDebug.LogError(ex.Message);
            }
        }

        protected static void CloseConsole(object sender, ConsoleCancelEventArgs e)
        {
            // throw new NotImplementedException();
            LogNetDebug.LogInfo("正常退出。。。。。。。。。。。");
            Environment.Exit(0);
        }

        static void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            //LogNetDebug.LogInfo("导致退出的事件:"+e);
            LogNetDebug.LogWarn("退出程序!");

        }

        /// <summary>
        /// 创建实例是否成功
        /// </summary>
        /// <param name="mutexName"></param>
        /// <returns></returns>
        public static bool CreateInstance(string mutexName)
        {
            bool createdNew;
            _ = new System.Threading.Mutex(true, mutexName, out createdNew);
            //if (!createdNew)
            //    Trace.WriteLine("Another instance is already running.");

            return createdNew;
        }

    }

}
